<template>
  <div class="scene-supervision">
    <div class="top">
      <div class="btn1">
        <span :class="{active:active=='1'}" @click="active='1'">时序图</span>
        <span :class="{active:active=='2'}" @click="active='2'">树形图</span>
      </div>
      <el-select
        v-model="sceneId"
        placeholder="当前执行场景名称"
        style="width: 245px"
      >
        <el-option
          v-for="(item) in dict"
          :key="item.sceneId"
          :label="item.sceneName"
          :value="item.sceneId"
        />
      </el-select>
      <div class="btn2">
        <!-- <button class="red"><img src="@/assets/img/u3229.svg">结束</button> -->
        <button @click="excHandler"><img src="@/assets/img/u3232.svg">执行</button>
        <button @click="excHandlerAll"><img src="@/assets/img/u3225.svg">执行全部</button>
        <!-- <button><img src="@/assets/img/u2877.svg">自检</button> -->
      </div>
    </div>
    <div class="box">
      <img src="@/assets/img/u2203.svg">
      <img src="@/assets/img/u2203.svg">
      <img src="@/assets/img/u2203.svg">
      <img src="@/assets/img/u2203.svg">
      <div class="content">
        <div v-show="active=='1'" style="height: 100%;position: relative;">
          <div id="_y2lrshww" class="pic" />
          <div v-if="activeNode" style="position: absolute;" :style="`top:${top}px;left:${left}px;`">
            <Card :data="activeNode" :dict1="dict1" :devicelist="devicelist" :machinelist="machinelist" @deleteNode="activeNode = null" />
          </div>
        </div>
        <div v-show="active=='2'" class="tree">
          <Tree
            v-model="activeNode"
            :tree-list="nodeData.sceneParentNodeManagerList"
            :dict1="dict1"
            :devicelist="devicelist"
            :machinelist="machinelist"
          />
        </div>
      </div>
      <div class="right">
        <RightBox :log-info="logInfo" />
      </div>
    </div>
  </div>
</template>

<script>
import RightBox from '@/views/scenceManage/sceneSupervision/RightBox.vue'
import Tree from '@/views/scenceManage/sceneSupervision/Tree'
// import { FlowChart } from '@/components/FlowChart/index.js'
import { createFDByData } from '@/components/FlowDraw/index'
import { getSceneList, getSceneDetail, performDetection } from '@/api/table'
// import { createCard } from './card'
import Card from './card/Card'
import { createConfirm } from '@/components/confirmModal'
import { getOperateDataByType } from '@/api/dict'
import { getDeviceList, getMachineList, editNodeStatus, getLog } from '@/api/table'
// import json from '@/components/FlowDraw/test2.json'

export default {
  name: 'SceneSupervision',
  components: {
    Card,
    RightBox,
    Tree
  },
  data() {
    return {
      active: '1',
      sceneId: '',
      dict: [],

      nodeData: {},
      dict1: [],
      devicelist: [],
      machinelist: [],
      top: 0,
      left: 0,
      activeNode: null,
      /** 执行任务日志 */
      logInfo: []
    }
  },
  watch: {
    sceneId(id) {
      console.log('id', id)
      this.activeNode = null
      this.getData(id).then(res => {
        this.draw(this.nodeData)
      })
      this.getLog()
    },
    nodeData(val) {
      this.fd.updateStatus(val)
    },
    activeNode(val) {
      this.fd.updateActiveRect(val?.nodeId)
    },
    active() {
      this.activeNode = null
    }
  },
  mounted() {
    this.init()
    this.getList()
    this.getDict1()
    // this.nodeData = json
    // this.draw(this.nodeData)
  },
  methods: {
    init() {
      const fd = createFDByData('_y2lrshww')
      fd.ref.onActive = (node) => {
        // console.log('node', node)
        if (node) {
          this.top = node.offsetY
          this.left = node.offsetX
        }
        this.activeNode = node?.node
      }
      this.fd = fd
    },
    draw(data) {
      this.fd.draw(data)
    },
    getList() {
      getSceneList({ pageSize: 100000 }).then(res => {
        console.log('abc', res)
        if (res.code === 200) {
          this.dict = res.rows
        }
      })
    },
    getData(sceneId) {
      return new Promise((resolve, reject) => {
        getSceneDetail({ sceneId }).then(res => {
          console.log('res', res)
          if (res.code === 200) {
            this.nodeData = res.data
            const loading = this.nodeData.sceneParentNodeManagerList?.some(i => {
              return i.sceneChildNodeManagerList?.some(x => {
                return x.executeStatus == 2
              })
            })
            resolve(loading)
          } else {
            reject()
          }
        })
      })
    },
    async excFn(node) {
      if (node) {
        const params = {
          childNodeId: node.childNodeId
        }
        if (node.nodeType == 4) {
          params.executeTime = Date.now()
        }
        const res = await performDetection(params)
        console.log('res11', res)
        if (res.code == 200) {
          this.getLog()
          return true
        } else {
          this.$message.error(res.msg || '出错了')
          throw new Error('出错了')
        }
      }
    },
    async excHandler() {
      if (!this.activeNode) return
      if (!(await this.confirmFn(this.activeNode))) return
      this.nodeData?.sceneParentNodeManagerList.some(i => {
        return i.sceneChildNodeManagerList.some(j => {
          if (this.activeNode.childNodeId == j.childNodeId) {
            j.executeStatus = '2'
            return true
          }
        })
      })
      this.nodeData = { ...this.nodeData }
      const loading = await this.excFn(this.activeNode)
      if (loading) {
        return new Promise((resolve, reject) => {
          const timer = setInterval(() => {
            fn()
          }, 3000)
          const fn = () => {
            this.getData(this.sceneId).then(res => {
              if (!res) {
                clearInterval(timer)
                this.$message.success(this.activeNode.childNodeName + ':执行成功')
                resolve()
              }
            })
          }
          fn()
        })
      }
    },
    async excHandlerAll() {
      this.left = -99999
      for (let i = 0; i < this.nodeData.sceneParentNodeManagerList.length; i++) {
        const node = this.nodeData.sceneParentNodeManagerList[i]
        if (node.sceneChildNodeManagerList?.length) {
          const n = node.sceneChildNodeManagerList
          for (let j = 0; j < n.length; j++) {
            const n1 = n[j]
            if (j == 0) {
              n1.checkOne = 0
            }
            this.activeNode = n1
            await this.excHandler()
          }
        }
      }
    },
    /** 如果节点类型是2，则需要确认是否执行 */
    async confirmFn(node) {
      let flag = true
      if (node.nodeType == 2) {
        console.log('node', node)
        const result = await new Promise((resolve, reject) => {
          createConfirm({
            title: '确认执行？',
            nodeName: node.childNodeName,
            content: `描述：${node.remark}`,
            async ok() {
              const res = await editNodeStatus({ ...node, executeStatus: '1' })
              if (res.code == 200) {
                resolve(true)
              }
            },
            cancel() {
              resolve(false)
            }
          })
        })
        console.log('result', result)
        flag = result
      }
      return flag
    },
    /** 获取当前场景的执行日志记录 */
    getLog() {
      getLog(this.sceneId).then((res) => {
        // console.log('日志', res)
        if (res.code == 200) {
          this.logInfo = res.data?.reverse()
        }
      })
    },
    getDict1() {
      getOperateDataByType().then((res) => {
        console.log('节点类型', res)
        this.dict1 = res.data
      })
      getDeviceList({
        pageSize: 1,
        pageNum: 1000
      }).then((res) => {
        this.devicelist = res.rows
      })
      getMachineList({
        pageSize: 1,
        pageNum: 1000
      }).then((res) => {
        this.machinelist = res.rows
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.scene-supervision {
  flex-direction: column;
  height: calc(100vh - 64px);
  padding: 20px;
  color: #fff;
  font-family: "microsoft yahei";
  .top {
    display: flex;
    margin-bottom: 20px;
    .btn1 {
      display: flex;
      margin-right: 20px;
      &>span {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100px;
        height: 32px;
        cursor: pointer;
        background: #1d435f;
        &.active {
          border: 1px solid #00c2ff;
          box-shadow: 0px 0px 9px 0px rgba(0, 194, 255, 1) inset;
        }
      }
    }
    .btn2 {
      display: flex;
      flex: 1;
      justify-content: flex-end;
      gap: 20px;
      button {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 32px;
        padding: 0 15px;
        cursor: pointer;
        color: #fff;
        border: 1px solid #00c2ff;
        border-radius: 4px;
        background: #1d435f;
        box-shadow: 0px 0px 10px 0px rgba(0, 194, 255, 1) inset;
        gap: 3px;
        &:hover {
          opacity: .8;
        }
      }
      .red {
        border: 1px solid #fa5151;
        background: #400b0b;
        box-shadow: 0px 0px 10px 0px rgba(250, 81, 81, 1) inset;
      }
    }
  }
  .box {
    position: relative;
    height: calc(100% - 40px);
    padding: 22px;
    background: rgba(0, 194, 255,.149);
    &>img {
      position: absolute;
    }
    &>img:nth-of-type(1) {
      top: 0;
      left: 0;
    }
    &>img:nth-of-type(2) {
      top: 0;
      right: 0;
      transform: rotate(90deg);
    }
    &>img:nth-of-type(3) {
      right: 0;
      bottom: 0;
      transform: rotate(180deg);
    }
    &>img:nth-of-type(4) {
      bottom: 0;
      left: 0;
      transform: rotate(270deg);
    }
    .content {
      height: 100%;
      border: 1px solid #637e8a;
      background: #182531;
      .pic,
      .tree {
        height: 100%;
      }
    }
    .right {
      position: absolute;
      top: 20px;
      right: 20px;
      width: 460px;
      height: calc(100% - 40px);
      padding: 20px 20px 20px 0;
      // border: 1px solid red;
    }
  }
}
::v-deep {
  .el-input__inner {
    color: white;
    border-color: #0c7ca5;
    background: #153044;
  }
}
</style>
